package com.radioapp.liaoliaobao.module.user.auth;

import com.jaydenxiao.common.base.BasePresenter;
import com.jaydenxiao.common.baserx.RxHelper;
import com.jaydenxiao.common.baserx.RxSubscriber;
import com.jaydenxiao.common.manager.ServiceManager;
import com.radioapp.liaoliaobao.api.UserService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 功能：
 * 描述
 * Created by yue on 2019-10-08
 */
public class AuthApplyPresenter extends BasePresenter<AuthApplyView> {


    /**
     * 认证
     *
     * @param path
     * @param alipay_account
     * @param alipay_realname
     */
    public void verify(String path, String alipay_account, String alipay_realname) {
        //转换图片
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("image/png"), new File(path));
        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", new File(path).getName(), requestFile);

        List<MultipartBody.Part> parts = new ArrayList<>();
        parts.add(toRequestBodyOfText("alipay_account", alipay_account));
        parts.add(toRequestBodyOfText("alipay_realname", alipay_realname));
        parts.add(toRequestBodyOfImage("file",new File(path)));

        ServiceManager.create(UserService.class)
                .verify(parts)
                .compose(mView.bindToLife())
                .compose(RxHelper.handleFlatMap())
                .subscribe(new RxSubscriber<String>(mContext, true) {
                    @Override
                    protected void subscribe(Disposable d) {
                        addSubscribe(d);
                    }

                    @Override
                    protected void _onNext(String s) {
                        mView.success();
                    }

                    @Override
                    protected void _TokenInvalid() {
                        mView.tokenInvalid();
                    }

                });
    }




    private MultipartBody.Part toRequestBodyOfText (String keyStr, String value) {
        MultipartBody.Part body = MultipartBody.Part.createFormData(keyStr, value);
        return body;
    }

    private MultipartBody.Part toRequestBodyOfImage(String keyStr, File pFile){
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), pFile);
        MultipartBody.Part filedata = MultipartBody.Part.createFormData(keyStr, pFile.getName(), requestBody);
        return filedata;
    }
}
